from django.core.exceptions import ValidationError
from django.db import models
from django.urls import reverse
from ctbloge.apps.cms.models import Category, Tag
from ctbloge import settings
from ctbloge.apps.blog.models import BaseModel
from ctbloge.apps.cms.models import Article

class Resource(BaseModel):
    TYPE_CHOICES = (
        ('docs', '文档(PDF, Word, Excel, txt)'),
        ('code', '代码'),
        ('image', '图片(JPG, PNG, GIF, SVG)'),
        ('video', '视频(MP4, AVI, WMV, FLV, MPEG, M3U8, etc.)'),
        ('audio', '音频(MP3, WAV, OGG, etc.)'),
        ('zip','压缩包(ZIP, RAR, etc.)'),
        ('other', '其他类型'),
    )

    title = models.CharField('资源名称', max_length=100, unique=True)
    desc = models.TextField('资源描述', blank=True, default='')  # 改为TextField且不允许null
    content = models.TextField('介绍内容')
    image = models.ImageField(
        '展示图片',
        upload_to='resource/%Y/%m/%d',
        default='default/resource/resource_default.png',
        blank=True,
        help_text='推荐尺寸：600x400像素'
    )
    file = models.FileField(
        '资源文件',
        upload_to='resource/%Y/%m/%d',
        help_text='最大文件大小100MB'
    )
    file_type = models.CharField(
        '资源类型',
        max_length=20,
        choices=TYPE_CHOICES,
        default='doc'
    )
    author = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name='作者', on_delete=models.CASCADE, related_name='resources')
    category = models.ForeignKey(
        Category,
        verbose_name='分类',
        on_delete=models.PROTECT,  # 防止误删分类
        related_name='resources'
    )
    tags = models.ManyToManyField(Tag, blank=True,verbose_name='标签')
    articles = models.ForeignKey(Article, blank=True,null=True, related_name='articles', on_delete=models.PROTECT,verbose_name='关联文章')
    download_count = models.PositiveIntegerField('下载次数', default=0, editable=False)
    is_public = models.BooleanField('是否展示', default=True)

    def get_file_type_display(self):
        return dict(self.TYPE_CHOICES).get(self.file_type, '未知类型')
    class Meta:
        verbose_name = '资源'
        verbose_name_plural = verbose_name
        ordering = ['-created_date']
        indexes = [
            models.Index(fields=['-download_count']),
            models.Index(fields=['file_type']),
        ]

    def get_absolute_url(self):
        return reverse('resource_detail', kwargs={'pk': self.pk})

    def __str__(self):
        return f"{self.title} ({self.get_file_type_display()})"

class FavSite(BaseModel):  # 继承BaseModel
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        verbose_name='用户',
        on_delete=models.CASCADE,
        related_name='fav_sites'
    )
    name = models.CharField('网站名称', max_length=100)  # 新增名称字段
    site_url = models.URLField('网站地址', max_length=500)
    desc = models.CharField('网站描述', max_length=200, blank=True)

    #分类
    category = models.ForeignKey(
        Category,
        verbose_name='分类',
        on_delete=models.PROTECT,  # 防止误删分类
        related_name='fav_sites'
    )
    icon = models.CharField('网站图标', max_length=200, blank=True)
    image = models.ImageField(
        '展示图片',
        upload_to='fav_site/%Y-%m-%d/',
        blank=True,
    )
    is_public = models.BooleanField('公开可见', default=True)

    def get_site_icon(self):
        if self.icon:
            return self.icon
        return f"https://{self.site_url}/favicon.ico"
    def __str__(self):
        return self.name
    class Meta:
        verbose_name = '收藏网站'
        verbose_name_plural = verbose_name
        unique_together = [('user', 'site_url')]  # 防止重复收藏
        ordering = ['-rank', '-created_date']

class Tool(BaseModel):  # 继承BaseModel
    name = models.CharField('工具名称', max_length=50, unique=True)
    desc = models.CharField('功能描述', max_length=200)
    link = models.URLField('链接', max_length=100,blank=True,null=True)
    route = models.CharField('路由', max_length=50, blank=True,null=True)
    image = models.ImageField(
        '展示图片',
        upload_to='tools/',
        blank=True,
        help_text='推荐尺寸：600x400像素',
        default='default/resource/resource_default.png',
    )
    #分类
    category = models.ForeignKey(
        Category,
        verbose_name='分类',
        on_delete=models.PROTECT,  # 防止误删分类
        related_name='tools'
    )
    is_official = models.BooleanField('官方工具', default=False)
    programming_language = models.CharField('编程语言', max_length=50, blank=True)

    class Meta:
        verbose_name = '工具'
        verbose_name_plural = verbose_name
        ordering = ['-rank', 'name']
    def __str__(self):
        return self.name
    def save(self, *args, **kwargs):
        if self.link and self.route:
            raise ValidationError('link和route不能同时填写')
        super().save(*args, **kwargs)
